package repository

import (
	"fmt"
	"gin-shop-admin/dao"
	"gin-shop-admin/models"
	"strconv"
	"strings"
	"time"
)

func GetGoodsList(query string, pageNum string, pageSize string) (goods []models.Goods, total int, err error) {
	if query == "" {
		if pageSize != "" && pageNum != ""{
			page_num,_ := strconv.Atoi(pageNum)
			page_size,_ := strconv.Atoi(pageSize)
			dao.DB.Model(&models.Goods{}).Where("is_del=?", "0").Count(&total)
			if err = dao.DB.Where("is_del=?", "0").Limit(page_size).Offset((page_num-1)*page_size).Find(&goods).Error; err!=nil{
				return nil,total,err
			}
		}else {
			if err = dao.DB.Where("is_del=?", "0").Find(&goods).Count(&total).Error;err!=nil{
				return nil, 0,err
			}
		}
	}else {
		if pageSize != "" && pageNum != ""{
			page_num,_ := strconv.Atoi(pageNum)
			page_size,_ := strconv.Atoi(pageSize)
			dao.DB.Model(&models.Goods{}).Where("is_del = '0' and goods_name like ?", "%" +query+"%").Count(&total)
			if err = dao.DB.Debug().Where("is_del = '0' and goods_name like ?", "%"+query+"%").Limit(page_size).Offset((page_num-1)*page_size).Find(&goods).Error; err!= nil{
				return nil,total,err
			}
		}else {
			if err = dao.DB.Where("is_del = '0' and goods_name like ?", "%" + query + "%").Find(&goods).Count(&total).Error;err!= nil{
				return nil, 0, err
			}
		}
	}
	return
}

func DeleteOneGoods(id int) error {
	return dao.DB.Model(&models.Goods{ID:id}).UpdateColumn(&models.Goods{IsDel:"1", DeleteTime:time.Now().Unix()}).Error
	//return dao.DB.Delete(&models.Goods{ID:id}).Error
}

func AddOneGoods(goods_form models.GoodsForm) (err error) {
	price, _ := strconv.ParseFloat(goods_form.GoodsPrice, 64)
	goods_num, _ := strconv.Atoi(goods_form.GoodsNumber)
	goods_weight, _ := strconv.Atoi(goods_form.GoodsWeight)
	cat_ids := strings.Split(goods_form.GoodsCat, ",")
	cat_one_id, _  := strconv.Atoi(cat_ids[0])
	cat_two_id, _  := strconv.Atoi(cat_ids[1])
	cat_three_id, _  := strconv.Atoi(cat_ids[2])
	var goods  = models.Goods{
		Name:goods_form.GoodsName,
		Price:price,
		Number:goods_num,
		Weight:goods_weight,
		Introduce:goods_form.GoodsIntroduce,
		CatOneID:cat_one_id,
		CatTwoID:cat_two_id,
		CatThreeID:cat_three_id,
		CatID:cat_three_id,
		AddTime:time.Now().Unix(),
	}
	if err = dao.DB.Create(&goods).Error;err != nil{
		return
	}
	fmt.Println(goods)
	for _, attr := range goods_form.Attrs{
		err = dao.DB.Create(&models.GoodsAttr{AttrID:attr.AttrID, AttrValue:attr.AttrValue, GoodsID:goods.ID}).Error
		if err != nil {
			fmt.Println(err)
		}
	}
	for _, pic := range goods_form.Pics{
		err = dao.DB.Create(&models.GoodsPics{GoodsID:goods.ID,PicsBig:pic["pic"],PicsMid:pic["pic"],PicsSma:pic["pic"]}).Error
		if err != nil {
			fmt.Println(err)
		}
	}
	return
}

